//
//  HomeViewController.m
//  beautyAccompany
//
//  Created by xiaocankeji on 15/11/3.
//  Copyright © 2015年 xiaocankeji. All rights reserved.
//

#import "HomeViewController.h"
#import "LoginViewController.h"
#import "ChatListViewController.h"
#import "MeViewController.h"
#import "ChatViewController.h"
#import "Order.h"
#import "DataSigner.h"
#import <AlipaySDK/AlipaySDK.h>
#import "OrderListViewController.h"
#import "CallViewController.h"
#import "FoundOrderViewController.h"
#import "MapSearchViewController.h"
#import "SetViewController.h"
#import "CycleScrollView.h" //专辑


#import "NearbyView.h"
#import "CategoryView.h"

#define kNearbyViewHeight 75
#define kCategoryViewHeight (DeviceWidth/3*2)


//两次提示的默认间隔
static const CGFloat kDefaultPlaySoundInterval = 10.0;
static NSString *kMessageType = @"MessageType";
static NSString *kConversationChatter = @"ConversationChatter";
@interface HomeViewController ()<IChatManagerDelegate, EMCallManagerDelegate,MapSearchViewControllerDelegate>


@property (strong, nonatomic) NSDate *lastPlaySoundDate;
@property (strong, nonatomic) UILabel *mesRedLabel;
@property (strong, nonatomic) CycleScrollView *topicScrollView;
@property (strong, nonatomic) NSMutableArray *topicViews;//专辑图片数组
@property (strong, nonatomic) NearbyView *nearbyView;//附近

@property (strong, nonatomic) CycleScrollView *categoryScrollView;//类别
@property (strong, nonatomic) NSMutableArray *categoryViews;//分类的数组


@end


@implementation HomeViewController
- (NSMutableArray *)topicViews
{
    if (nil == _topicViews) {
        _topicViews = [NSMutableArray array];
    }
    return _topicViews;
}
- (NSMutableArray *)categoryViews
{
    if (nil == _categoryViews) {
        _categoryViews = [NSMutableArray array];
    }
    return _categoryViews;
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.navigationController.navigationBar.hidden = YES;
    
    MPUser *user = [MPUser currentUser];
    
    if (user&& user.isUserInited) {
        
    }else{
        // 如果用户已填写了初始化信息
        UINavigationController *Login = [[UINavigationController alloc]initWithRootViewController:[[LoginViewController alloc]init]];
        Login.modalPresentationStyle = UIModalPresentationFormSheet;
        [self presentViewController:Login animated:NO completion:nil];    }
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    self.navigationController.navigationBar.hidden = NO;
}

//我的
- (void)clickLeftBt
{
   
    CATransition *transition = [CATransition animation];
    transition.duration = 0.4;
    transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    transition.type = kCATransitionPush;
    transition.subtype = kCATransitionFromLeft;
    transition.delegate = self;
    [self.navigationController.view.layer addAnimation:transition forKey:nil];
    
     MeViewController *meVC = [MeViewController meViewController];
    [self.navigationController pushViewController:meVC animated:YES];
}



//消息
- (void)clickRightBt
{
    [Utils pushTabbarHidden:[ChatListViewController chatlistViewController] Selfvc:self];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.hidden = YES;
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = RGBA(229, 229, 229, 1);
    //专辑
    _topicScrollView = [[CycleScrollView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, DeviceHeight - kNearbyViewHeight - kCategoryViewHeight) animationDuration:3];
    _topicScrollView.pageType = 1;
    _topicScrollView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_topicScrollView];
    [self setTopicContent];
    
    UIButton *leftBT = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBT.frame = CGRectMake(20, 20, 60, 60);
    leftBT.backgroundColor = [UIColor clearColor];
    [leftBT setTitle:@"我的" forState:UIControlStateNormal];
    //[leftBT setTitleColor:RGBA(88, 88, 88, 1) forState:UIControlStateNormal];
    leftBT.titleLabel.font = kFont(18);
    [leftBT addTarget:self action:@selector(clickLeftBt) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:leftBT];
    
    
    UIButton *rightBT = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBT.frame = CGRectMake(DeviceWidth - 80 , 20, 60, 60);
    rightBT.backgroundColor = [UIColor clearColor];
    [rightBT setTitle:@"消息" forState:UIControlStateNormal];
   // [rightBT setTitleColor:RGBA(88, 88, 88, 1) forState:UIControlStateNormal];
    rightBT.titleLabel.font = kFont(18);
    [rightBT addTarget:self action:@selector(clickRightBt) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:rightBT];
    
    
    
    //附近
    _nearbyView = [[NearbyView alloc] initWithFrame:CGRectMake(0, DeviceHeight - kNearbyViewHeight - kCategoryViewHeight-5, DeviceWidth, kNearbyViewHeight-5)];
    UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickNearbtView)];
    [_nearbyView addGestureRecognizer:tapGR];
    [self.view addSubview:_nearbyView];

    //类别
    _categoryScrollView = [[CycleScrollView alloc] initWithFrame:CGRectMake(0, DeviceHeight - kCategoryViewHeight, DeviceWidth, kCategoryViewHeight)];
    _categoryScrollView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_categoryScrollView];
    [self setCategoryContent];
//    self.view.backgroundColor = APPCOLORBACKGROUNDCOLOR(1);
//    
//    UILabel *l = [[UILabel alloc] initWithFrame:CGRectMake(100, 100, 100, 100)];
//    l .text = @"主页";
//    l .textColor = [UIColor blackColor];
//    [self.view addSubview:l];
//    
//    UIButton *bt = [UIButton buttonWithType:UIButtonTypeCustom];
//    bt.frame = CGRectMake(200, 200, 100, 100);
//    bt.backgroundColor = [UIColor blackColor];
//    [bt setTitle:@"列表" forState:UIControlStateNormal];
//    [bt addTarget:self action:@selector(clickBT) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:bt];
//    
//    _mesRedLabel = [[UILabel alloc] initWithFrame:CGRectMake(80, 0, 20, 20)];
//    _mesRedLabel.text = @"";
//    _mesRedLabel.font = kFont(12);
//    _mesRedLabel.textAlignment = NSTextAlignmentCenter;
//    _mesRedLabel.layer.cornerRadius = 10;
//    _mesRedLabel.layer.masksToBounds = YES;
//    _mesRedLabel .textColor = [UIColor whiteColor];
//    _mesRedLabel.backgroundColor = [UIColor redColor];
//    _mesRedLabel.hidden = YES;
//    [bt addSubview:_mesRedLabel];
//    
//    
//     _chatListVC = [[ChatListViewController alloc] initWithNibName:nil bundle:nil];
//    
//    UIButton *bt1 = [UIButton buttonWithType:UIButtonTypeCustom];
//    bt1.frame = CGRectMake(20, 200, 100, 100);
//    bt1.backgroundColor = [UIColor blackColor];
//    [bt1 setTitle:@"聊天" forState:UIControlStateNormal];
//    [bt1 addTarget:self action:@selector(clickChat) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:bt1];
//    
//    //
//   
//    
//    
//    UIButton *bt2 = [UIButton buttonWithType:UIButtonTypeCustom];
//    bt2.frame = CGRectMake(20, 310, 100, 100);
//    bt2.backgroundColor = [UIColor blackColor];
//    [bt2 setTitle:@"支付0.01" forState:UIControlStateNormal];
//    [bt2 addTarget:self action:@selector(clickAliPay) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:bt2];
//    
//    
//    
//    UIButton *bt3 = [UIButton buttonWithType:UIButtonTypeCustom];
//    bt3.frame = CGRectMake(200, 310, 100, 100);
//    bt3.backgroundColor = [UIColor blackColor];
//    [bt3 setTitle:@"订单" forState:UIControlStateNormal];
//    [bt3 addTarget:self action:@selector(clickOrder) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:bt3];
//    
//    
//    UIButton *bt4 = [UIButton buttonWithType:UIButtonTypeCustom];
//    bt4.frame = CGRectMake(20, 420, 100, 100);
//    bt4.backgroundColor = [UIColor blackColor];
//    [bt4 setTitle:@"地图" forState:UIControlStateNormal];
//    [bt4 addTarget:self action:@selector(clickMap) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:bt4];
//    
//    
//    
//    UIButton *bt5 = [UIButton buttonWithType:UIButtonTypeCustom];
//    bt5.frame = CGRectMake(200, 420, 100, 100);
//    bt5.backgroundColor = [UIColor blackColor];
//    [bt5 setTitle:@"设置" forState:UIControlStateNormal];
//    [bt5 addTarget:self action:@selector(clickSet) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:bt5];
    
    
    
#warning 把self注册为SDK的delegate
    [self registerNotifications];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(callOutWithChatter:) name:@"callOutWithChatter" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(callControllerClose:) name:@"callControllerClose" object:nil];
    // Do any additional setup after loading the view.
}


#pragma mark 附近的美陪师
- (void)clickNearbtView
{
    [HUD Prompt:@"附近的美陪师"];
}
//
#pragma mark 设置专辑内容视图和点击事件
- (void)setTopicContent
{
    [self.topicViews removeAllObjects];

    
    for (int i = 0; i<4; i++) {
        CGFloat h = DeviceHeight - kNearbyViewHeight - kCategoryViewHeight;
        UIImageView *topicImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, h)];
        [topicImageView setContentMode:UIViewContentModeScaleAspectFill];
        topicImageView.image = [UIImage imageNamed:@"背景"];
        
        [self.topicViews addObject:topicImageView];
    }
    [self setTopicContentViews];

}
- (void)setTopicContentViews
{
    __weak __typeof(self) weakSelf = self;
    self.topicScrollView.fetchContentViewAtIndex = ^UIView *(NSInteger pageIndex){
        
        if (pageIndex > weakSelf.topicViews.count) {
            return weakSelf.topicViews[0];
        }else{
            return weakSelf.topicViews[pageIndex];
        }
    };
    //设置个数
    self.topicScrollView.totalPagesCount = ^NSInteger(void){
        return [weakSelf.topicViews count];
    };
    //设置点击事件
    self.topicScrollView.TapActionBlock = ^(NSInteger pageIndex){
        [HUD Prompt:[NSString stringWithFormat:@"点击第%ld个",pageIndex+1]];
    };
    
}
#pragma mark 设置类别内容视图和点击事件
- (void)setCategoryContent
{
    
    [self.categoryViews removeAllObjects];
    
    
    __weak __typeof(self) weakSelf = self;
    
    AVQuery *categoryQuery = [MPCategory query];
    [categoryQuery whereKey:@"status" equalTo:[NSNumber numberWithInteger:1]];
    [categoryQuery orderByAscending:@"priority"];
    categoryQuery.cachePolicy = kAVCachePolicyNetworkElseCache;
    [categoryQuery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
        if (error) {
            
        }else{
            for (int i = 0; i<((objects.count-1)/6+1); i++) {
                NSLog(@"%lu",objects.count/6);
                NSInteger count = 6;
                if (i == objects.count/6) {
                    count = objects.count - 6*i;
                }
                
                UIView *chunkView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, DeviceWidth, kCategoryViewHeight)];
                chunkView.backgroundColor = [UIColor whiteColor];
                for (int j = 0; j< count ; j++) {
                    NSLog(@"%d",j+6*i);
                    
                    CategoryView *categoryView = [[CategoryView
                                                   alloc] initCategoryView];
                    
                    categoryView.frame = CGRectMake(j%3*kCategoryViewHeight/2, j/3*kCategoryViewHeight/2, kCategoryViewHeight/2, kCategoryViewHeight/2);
                    categoryView.category = (MPCategory *)objects[j+6*i];
                    [categoryView addTarget:self action:@selector(clickCategory:) forControlEvents:UIControlEventTouchUpInside];
                    
                    [chunkView addSubview:categoryView];
                    
                    
                    
                }
               
                CGFloat h1 = kCategoryViewHeight;
                CGFloat h2 = kCategoryViewHeight;
                CGFloat w = DeviceWidth;
                
                
                if (count != 6) {
                    
                    switch (count) {
                        case 0:
                            h1 = 0;
                            h2 = 0;
                            w = 0;
                            break;
                        case 1:
                            h1 = kCategoryViewHeight/2;
                            h2 = 0;
                            w = DeviceWidth/3;
                            break;
                        case 2:
                            h1 = kCategoryViewHeight/2;
                            h2 = kCategoryViewHeight/2;
                            w = DeviceWidth/3*2;
                            break;
                        case 3:
                            h1 = kCategoryViewHeight/2;
                            h2 = kCategoryViewHeight/2;
                            w = DeviceWidth;
                            break;
                        case 4:
                            h1 = kCategoryViewHeight;
                            h2 = kCategoryViewHeight/2;
                            w = DeviceWidth;
                            break;
                        case 5:
                            h1 = kCategoryViewHeight;
                            h2 = kCategoryViewHeight;
                            w = DeviceWidth;
                            break;
                        case 6:
                            h1 = kCategoryViewHeight;
                            h2 = kCategoryViewHeight;
                            w = DeviceWidth;
                            break;
                            
                        default:
                            break;
                    }
                    
                    
                    
                    
                    
                }
                
                
                    UIView *line1 = [[UIView alloc] initWithFrame:CGRectMake((DeviceWidth-1)/3, 0, 0.5, h1)];
                    line1.backgroundColor = RGBA(222, 222, 222, 1);
                    [chunkView addSubview:line1];
                    
                    UIView *line2 = [[UIView alloc] initWithFrame:CGRectMake((DeviceWidth-1)/3*2, 0, 0.5, h2)];
                    line2.backgroundColor = RGBA(222, 222, 222, 1);
                    [chunkView addSubview:line2];
                    
                    UIView *line3 = [[UIView alloc] initWithFrame:CGRectMake(0, (kCategoryViewHeight-1)/2, w , 0.5)];
                    line3.backgroundColor = RGBA(222, 222, 222, 1);
                    [chunkView addSubview:line3];
                
                
                
                
                
                
                
                
                [self.categoryViews addObject:chunkView];
                
            }
            [weakSelf setCategoryContentViews];
            
        }

    }];
    
    
    
}
- (void)setCategoryContentViews
{
    __weak __typeof(self) weakSelf = self;
    self.categoryScrollView.fetchContentViewAtIndex = ^UIView *(NSInteger pageIndex){
        
        if (pageIndex > weakSelf.categoryViews.count) {
            return weakSelf.categoryViews[0];
        }else{
            return weakSelf.categoryViews[pageIndex];
        }
    };
    
    //设置个数
    self.categoryScrollView.totalPagesCount = ^NSInteger(void){
        
        if (weakSelf.categoryViews.count<2) {
            weakSelf.categoryScrollView.pageControl.hidden = YES;
            weakSelf.categoryScrollView.cellview.hidden = YES;
        }else{
            weakSelf.categoryScrollView.pageControl.hidden = NO;
            weakSelf.categoryScrollView.cellview.hidden = NO;
        }
        
        return [weakSelf.categoryViews count];
    };
}


- (void)clickCategory:(CategoryView *)categoryView
{
    [HUD Prompt:[NSString stringWithFormat:@"%@",categoryView.category.title]];
    
    FoundOrderViewController *foundOrderVC = [[FoundOrderViewController alloc] init];
    foundOrderVC.category = categoryView.category;
    [Utils pushTabbarHidden:foundOrderVC Selfvc:self];
    
}
- (void)clickSet
{
    [Utils pushTabbarHidden:[[SetViewController alloc] init] Selfvc:self];
}
- (void)clickMap
{
  
  
   MapSearchViewController *mapSearchVC = [[MapSearchViewController alloc] init];
    mapSearchVC.delegate = self;
    
    UIBarButtonItem *customLeftBarButtonItem = [[UIBarButtonItem alloc] init];
    customLeftBarButtonItem.title = @"返回";
    self.navigationItem.backBarButtonItem = customLeftBarButtonItem;
    [self.navigationController pushViewController:mapSearchVC animated:YES];
  //  [Utils pushTabbarHidden:mapSearchVC Selfvc:self];
}
- (void)selectCity:(NSString *)city Location:(NSString *)location
{
    [HUD Prompt:[NSString stringWithFormat:@"选择位置是%@,%@",city,location]];
}
- (void)clickOrder
{
    OrderListViewController *orderVC = [[OrderListViewController alloc] init];
   
    [Utils pushTabbarHidden:orderVC Selfvc:self];
    
}
- (void)clickAliPay
{
    //    NSString *partner = @"2088811117366572";
    //    NSString *seller = @"2394814529@qq.com";
    //    //str = [str ];
    //
    //    NSString *privateKey = @"MIICWwIBAAKBgQCWGsPWtMaC9SwyEyAQONMEKBeTo+ZM0rG34vyCTx5Fw8IC/QBa4N9GV5UQgNSj7D8ItjsDGpAOdFTi0snmejZipcNdzljhmHccbGaYwbYxBAPKY7kHmQ2yGKQOBJ7/h7G0CiWLpW1tta39PsQk+9pCGQWoOi0Q2CcYZyQ6wf8hewIDAQABAoGAdClAVv7NBPlw+0t7q7Id8wCHxlS3W8pNiA3b9Yf+2GR21tMuHCYcA5axn/TjGfwwh7BmmK9MvjLeoi4X2wnG3X8cBgWJF+x7Pwe59ISnbLCYe5j46GpK8nB9XrUcR7mi4ults8ESvKXGPuT64nmLKa+NeISi7CZB1SE5LDmnnxkCQQDFD7+z1k2ya8EqIka7L9Xb0c2JaYzrPTJvmy93C60CalLeHxoKXhzLDQ6ql1zswFwjhEvvfCewh0WXsrBrr0kFAkEAwv+zHSy0kaW4WimRGjxulxnDYiOorUhZw//+oNJ1cgyjP61wLvPZLe3W0EC2VGBhzcEpe144xmWu3a+1qWbIfwJASyp0rv4haNsdNRsZ67CVXGGsiquOKvSO1m9VLY1wkqlHrp4iaq33QaRbYcqWkV/WRV3jMRgkc3tFmlV4YbrcmQJAGPavMX71pue2UCSeJOOzrLhpoPi7sWNfyo3NRT1sN6uSgqZrhDdHiG+4XnTKYsbr/nFKJDcNwahm2I6UDRnRdQJAYrKFT1U0r7Xcj/QrTaU/WPMK4shxO3SaI1koszMBqzktGcKnN2l3Cv9veqmqQizK4gpBTY+NqCvMKpwMcQ6tNA==";
    //pkcs8
    /*
     *生成订单信息及签名
     */
    //将商品信息赋予AlixPayOrder的成员变量
    
    CGFloat price = 0.01;
    
   
    
    Order *order = [[Order alloc] init];
    order.partner = AlipayPARTNER;
    order.seller = AlipaySELLER;
    NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
    [formatter setDateFormat:@"yyyyMMdd"];
    NSString *date = [formatter stringFromDate:[NSDate date]];
    NSInteger number = (arc4random() % 100000000)+10000000;
    NSString *tradeID = [NSString stringWithFormat:@"%@%ld",date,(long)number];
    order.tradeNO = tradeID; //订单ID（由商家自行制定）
    order.productName = [NSString stringWithFormat:@"充值%.2f元",price];//product.subject; //商品标题
    //order.productDescription = [NSString stringWithFormat:@"%ld¥",(long)price]; //商品描述
    order.amount = [NSString stringWithFormat:@"%.2f",price]; //商品价格//
    //order.notifyURL =  @"http://192.168.1.5/usp/base/payment/alinotify"; //回调URL
    order.service = @"mobile.securitypay.pay";
    order.paymentType = @"1";
    order.inputCharset = @"utf-8";
    order.itBPay = @"30m";
    order.showUrl = @"m.alipay.com";
    
    //应用注册scheme,在AlixPayDemo-Info.plist定义URL types
    NSString *appScheme = @"alipayMeiPei";
    
    //将商品信息拼接成字符串
    NSString *orderSpec = [order description];
    NSLog(@"orderSpec = %@",orderSpec);
    //获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
    id<DataSigner> signer = CreateRSADataSigner(AlipayRSA_PRIVATE);
    NSString *signedString = [signer signString:orderSpec];
    
    //将签名成功字符串格式化为订单字符串,请严格按照该格式
    NSString *orderString = nil;
    if (signedString != nil) {
        orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                       orderSpec, signedString, @"RSA"];
        
        [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
            NSLog(@"reslut = %@",resultDic);
            //如果成功,需要更改判断条件
            if ([[resultDic objectForKey:@"resultStatus"] isEqualToString:@"9000"]) {
                //保存充值记录
                //修改钱数
               
                [HUD Prompt:@"充值成功,需要修改用户资料"];
                
            }
            
            
        }];
    }
    
}
- (void)clickChat
{
    if ([[MPUser currentUser].objectId isEqualToString:@"563c063f00b0bf378b385c9e"]) {
        ChatViewController *chatController = [[ChatViewController alloc] initWithConversationChatter:@"5638803960b2824fdba8c48f" conversationType:eConversationTypeChat];
        [self.navigationController pushViewController:chatController animated:YES];
    }else{
        
        ChatViewController *chatController = [[ChatViewController alloc] initWithConversationChatter:@"563c063f00b0bf378b385c9e" conversationType:eConversationTypeChat];
        [self.navigationController pushViewController:chatController animated:YES];
    }
    
    
    
}
- (void)clickBT
{
   
    [Utils pushTabbarHidden:[ChatListViewController chatlistViewController] Selfvc:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
- (void)dealloc
{
    [self unregisterNotifications];
}
-(void)registerNotifications
{
    [self unregisterNotifications];
    
    [[EaseMob sharedInstance].chatManager addDelegate:self delegateQueue:nil];
    [[EaseMob sharedInstance].callManager addDelegate:self delegateQueue:nil];
}

-(void)unregisterNotifications
{
    [[EaseMob sharedInstance].chatManager removeDelegate:self];
    [[EaseMob sharedInstance].callManager removeDelegate:self];
}
// 统计未读消息数
-(void)setupUnreadMessageCount
{
    NSArray *conversations = [[[EaseMob sharedInstance] chatManager] conversations];
    NSInteger unreadCount = 0;
    for (EMConversation *conversation in conversations) {
        unreadCount += conversation.unreadMessagesCount;
    }
    
    //在此处统计聊天列表的未读数

    if(_mesRedLabel){
        if(unreadCount>0){
            _mesRedLabel.hidden = NO;
            _mesRedLabel.text = [NSString stringWithFormat:@"%i",(int)unreadCount];
        }else{
            _mesRedLabel.hidden = YES;
            _mesRedLabel.text = @"";
        }
    }
    
    
//    if (_chatListVC) {
//        if (unreadCount > 0) {
//            _chatListVC.tabBarItem.badgeValue = [NSString stringWithFormat:@"%i",(int)unreadCount];
//        }else{
//            _chatListVC.tabBarItem.badgeValue = nil;
//        }
//    }
    
    UIApplication *application = [UIApplication sharedApplication];
    [application setApplicationIconBadgeNumber:unreadCount];
}


#pragma mark - call

- (BOOL)canRecord
{
    __block BOOL bCanRecord = YES;
    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    if ([[[UIDevice currentDevice] systemVersion] compare:@"7.0"] != NSOrderedAscending)
    {
        if ([audioSession respondsToSelector:@selector(requestRecordPermission:)]) {
            [audioSession performSelector:@selector(requestRecordPermission:) withObject:^(BOOL granted) {
                bCanRecord = granted;
            }];
        }
    }
    
    if (!bCanRecord) {
        UIAlertView * alt = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"setting.microphoneNoAuthority", @"No microphone permissions") message:NSLocalizedString(@"setting.microphoneAuthority", @"Please open in \"Setting\"-\"Privacy\"-\"Microphone\".") delegate:self cancelButtonTitle:nil otherButtonTitles:NSLocalizedString(@"ok", @"OK"), nil];
        [alt show];
    }
    
    return bCanRecord;
}

- (void)callOutWithChatter:(NSNotification *)notification
{
    id object = notification.object;
    if ([object isKindOfClass:[NSDictionary class]]) {
        if (![self canRecord]) {
            return;
        }
        
        EMError *error = nil;
        NSString *chatter = [object objectForKey:@"chatter"];
        EMCallSessionType type = [[object objectForKey:@"type"] intValue];
        EMCallSession *callSession = nil;
        if (type == eCallSessionTypeAudio) {
            callSession = [[EaseMob sharedInstance].callManager asyncMakeVoiceCall:chatter timeout:50 error:&error];
        }
        else if (type == eCallSessionTypeVideo){
            if (![CallViewController canVideo]) {
                return;
            }
            callSession = [[EaseMob sharedInstance].callManager asyncMakeVideoCall:chatter timeout:50 error:&error];
        }
        
        if (callSession && !error) {
            [[EaseMob sharedInstance].callManager removeDelegate:self];
            
            CallViewController *callController = [[CallViewController alloc] initWithSession:callSession isIncoming:NO];
            callController.modalPresentationStyle = UIModalPresentationOverFullScreen;
            [self presentViewController:callController animated:NO completion:nil];
        }
        
        if (error) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"error", @"error") message:error.description delegate:nil cancelButtonTitle:NSLocalizedString(@"ok", @"OK") otherButtonTitles:nil, nil];
            [alertView show];
        }
    }
}

- (void)callControllerClose:(NSNotification *)notification
{
    //    AVAudioSession *audioSession = [AVAudioSession sharedInstance];
    //    [audioSession setCategory:AVAudioSessionCategoryPlayback error:nil];
    //    [audioSession setActive:YES error:nil];
    
    [[EaseMob sharedInstance].callManager addDelegate:self delegateQueue:nil];
}
#pragma mark - IChatManagerDelegate 消息变化

- (void)didUpdateConversationList:(NSArray *)conversationList
{
    [self setupUnreadMessageCount];
    [[ChatListViewController chatlistViewController] refreshDataSource];
}

// 未读消息数量变化回调
-(void)didUnreadMessagesCountChanged
{
    [self setupUnreadMessageCount];
}
//离线非透传消息接收完成
- (void)didFinishedReceiveOfflineMessages
{
    [self setupUnreadMessageCount];
}

- (void)didFinishedReceiveOfflineCmdMessages
{
    
}

- (BOOL)needShowNotification:(NSString *)fromChatter
{
    BOOL ret = YES;
    NSArray *igGroupIds = [[EaseMob sharedInstance].chatManager ignoredGroupIds];
    for (NSString *str in igGroupIds) {
        if ([str isEqualToString:fromChatter]) {
            ret = NO;
            break;
        }
    }
    
    return ret;
}

// 收到消息回调
-(void)didReceiveMessage:(EMMessage *)message
{
    
    
    //在此处增加红点
    
    BOOL needShowNotification = (message.messageType != eMessageTypeChat) ? [self needShowNotification:message.conversationChatter] : YES;
    if (needShowNotification) {
#if !TARGET_IPHONE_SIMULATOR
        
        //        BOOL isAppActivity = [[UIApplication sharedApplication] applicationState] == UIApplicationStateActive;
        //        if (!isAppActivity) {
        //            [self showNotificationWithMessage:message];
        //        }else {
        //            [self playSoundAndVibration];
        //        }
        UIApplicationState state = [[UIApplication sharedApplication] applicationState];
        switch (state) {
            case UIApplicationStateActive:
                [self playSoundAndVibration];
                break;
            case UIApplicationStateInactive:
                [self playSoundAndVibration];
                break;
            case UIApplicationStateBackground:
                [self showNotificationWithMessage:message];
                break;
            default:
                break;
        }
#endif
    }
}
//透传消息

-(void)didReceiveCmdMessage:(EMMessage *)message
{
    [self showHint:NSLocalizedString(@"receiveCmd", @"receive cmd message")];
}
//离线透传消息
- (void)didReceiveOfflineCmdMessages:(NSArray *)offlineCmdMessages
{
    
}

- (void)playSoundAndVibration{
    NSTimeInterval timeInterval = [[NSDate date]
                                   timeIntervalSinceDate:self.lastPlaySoundDate];
    if (timeInterval < kDefaultPlaySoundInterval) {
        //如果距离上次响铃和震动时间太短, 则跳过响铃
        NSLog(@"skip ringing & vibration %@, %@", [NSDate date], self.lastPlaySoundDate);
        return;
    }
    
    //保存最后一次响铃时间
    self.lastPlaySoundDate = [NSDate date];
    
    // 收到消息时，播放音频
    [[EMCDDeviceManager sharedInstance] playNewMessageSound];
    // 收到消息时，震动
    [[EMCDDeviceManager sharedInstance] playVibration];
}

- (void)showNotificationWithMessage:(EMMessage *)message
{
    EMPushNotificationOptions *options = [[EaseMob sharedInstance].chatManager pushNotificationOptions];
    //发送本地推送
    UILocalNotification *notification = [[UILocalNotification alloc] init];
    notification.fireDate = [NSDate date]; //触发通知的时间
    
    if (options.displayStyle == ePushNotificationDisplayStyle_messageSummary) {
        id<IEMMessageBody> messageBody = [message.messageBodies firstObject];
        NSString *messageStr = nil;
        switch (messageBody.messageBodyType) {
            case eMessageBodyType_Text:
            {
                messageStr = ((EMTextMessageBody *)messageBody).text;
            }
                break;
            case eMessageBodyType_Image:
            {
                messageStr = NSLocalizedString(@"message.image", @"Image");
            }
                break;
            case eMessageBodyType_Location:
            {
                messageStr = NSLocalizedString(@"message.location", @"Location");
            }
                break;
            case eMessageBodyType_Voice:
            {
                messageStr = NSLocalizedString(@"message.voice", @"Voice");
            }
                break;
            case eMessageBodyType_Video:{
                messageStr = NSLocalizedString(@"message.video", @"Video");
            }
                break;
            default:
                break;
        }
        NSDictionary *userDic =  [Utils getUserNicknameHeadurlObjectId:message.from];
        NSString *title = [userDic objectForKey:@"nickname"];
        if (title == nil) {
            title = @"";
        }
        if (message.messageType == eMessageTypeGroupChat) {
            NSArray *groupArray = [[EaseMob sharedInstance].chatManager groupList];
            for (EMGroup *group in groupArray) {
                if ([group.groupId isEqualToString:message.conversationChatter]) {
                    title = [NSString stringWithFormat:@"%@(%@)", message.groupSenderName, group.groupSubject];
                    break;
                }
            }
        }
        else if (message.messageType == eMessageTypeChatRoom)
        {
            NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
            NSString *key = [NSString stringWithFormat:@"OnceJoinedChatrooms_%@", [[[EaseMob sharedInstance].chatManager loginInfo] objectForKey:@"username" ]];
            NSMutableDictionary *chatrooms = [NSMutableDictionary dictionaryWithDictionary:[ud objectForKey:key]];
            NSString *chatroomName = [chatrooms objectForKey:message.conversationChatter];
            if (chatroomName)
            {
                title = [NSString stringWithFormat:@"%@(%@)", message.groupSenderName, chatroomName];
            }
        }
        
        notification.alertBody = [NSString stringWithFormat:@"%@:%@", title, messageStr];
    }
    else{
        notification.alertBody = NSLocalizedString(@"receiveMessage", @"you have a new message");
    }
    
#warning 去掉注释会显示[本地]开头, 方便在开发中区分是否为本地推送
    //notification.alertBody = [[NSString alloc] initWithFormat:@"[本地]%@", notification.alertBody];
    
    notification.alertAction = NSLocalizedString(@"open", @"Open");
    notification.timeZone = [NSTimeZone defaultTimeZone];
    NSTimeInterval timeInterval = [[NSDate date] timeIntervalSinceDate:self.lastPlaySoundDate];
    if (timeInterval < kDefaultPlaySoundInterval) {
        NSLog(@"skip ringing & vibration %@, %@", [NSDate date], self.lastPlaySoundDate);
    } else {
        notification.soundName = UILocalNotificationDefaultSoundName;
        self.lastPlaySoundDate = [NSDate date];
    }
    
    NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
    [userInfo setObject:[NSNumber numberWithInt:message.messageType] forKey:kMessageType];
    [userInfo setObject:message.conversationChatter forKey:kConversationChatter];
    notification.userInfo = userInfo;
    
    //发送通知
    [[UIApplication sharedApplication] scheduleLocalNotification:notification];
    //    UIApplication *application = [UIApplication sharedApplication];
    //    application.applicationIconBadgeNumber += 1;
}

#pragma mark - IChatManagerDelegate 登陆回调（主要用于监听自动登录是否成功）

- (void)didLoginWithInfo:(NSDictionary *)loginInfo error:(EMError *)error
{
    if (error) {
        NSString *hintText = NSLocalizedString(@"reconnection.retry", @"Fail to log in your account, is try again... \nclick 'logout' button to jump to the login page \nclick 'continue to wait for' button for reconnection successful");
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"prompt", @"Prompt")
                                                            message:hintText
                                                           delegate:self
                                                  cancelButtonTitle:NSLocalizedString(@"reconnection.wait", @"continue to wait")
                                                  otherButtonTitles:NSLocalizedString(@"logout", @"Logout"),
                                  nil];
        alertView.tag = 99;
        [alertView show];
        [[ChatListViewController chatlistViewController] isConnect:NO];
    }
}

#pragma mark - 自动登录回调

- (void)willAutoReconnect{
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    NSNumber *showreconnect = [ud objectForKey:@"identifier_showreconnect_enable"];
    if (showreconnect && [showreconnect boolValue]) {
        [self hideHud];
        [self showHint:NSLocalizedString(@"reconnection.ongoing", @"reconnecting...")];
    }
}

- (void)didAutoReconnectFinishedWithError:(NSError *)error{
    NSUserDefaults *ud = [NSUserDefaults standardUserDefaults];
    NSNumber *showreconnect = [ud objectForKey:@"identifier_showreconnect_enable"];
    if (showreconnect && [showreconnect boolValue]) {
        [self hideHud];
        if (error) {
            [self showHint:NSLocalizedString(@"reconnection.fail", @"reconnection failure, later will continue to reconnection")];
        }else{
            [self showHint:NSLocalizedString(@"reconnection.success", @"reconnection successful！")];
        }
    }
}

#pragma mark - ICallManagerDelegate

- (void)callSessionStatusChanged:(EMCallSession *)callSession changeReason:(EMCallStatusChangedReason)reason error:(EMError *)error
{
    if (callSession.status == eCallSessionStatusConnected)
    {
        EMError *error = nil;
        do {
            BOOL isShowPicker = [[[NSUserDefaults standardUserDefaults] objectForKey:@"isShowPicker"] boolValue];
            if (isShowPicker) {
                error = [EMError errorWithCode:EMErrorInitFailure andDescription:NSLocalizedString(@"call.initFailed", @"Establish call failure")];
                break;
            }
            
            if (![self canRecord]) {
                error = [EMError errorWithCode:EMErrorInitFailure andDescription:NSLocalizedString(@"call.initFailed", @"Establish call failure")];
                break;
            }
            
#warning 在后台不能进行视频通话
            if(callSession.type == eCallSessionTypeVideo && ([[UIApplication sharedApplication] applicationState] != UIApplicationStateActive || ![CallViewController canVideo])){
                error = [EMError errorWithCode:EMErrorInitFailure andDescription:NSLocalizedString(@"call.initFailed", @"Establish call failure")];
                break;
            }
            
            if (!isShowPicker){
                [[EaseMob sharedInstance].callManager removeDelegate:self];
                CallViewController *callController = [[CallViewController alloc] initWithSession:callSession isIncoming:YES];
                callController.modalPresentationStyle = UIModalPresentationOverFullScreen;
                [self presentViewController:callController animated:NO completion:nil];
                if ([self.navigationController.topViewController isKindOfClass:[ChatViewController class]])
                {
                    ChatViewController *chatVc = (ChatViewController *)self.navigationController.topViewController;
                    chatVc.isViewDidAppear = NO;
                }
            }
        } while (0);
        
        if (error) {
            [[EaseMob sharedInstance].callManager asyncEndCall:callSession.sessionId reason:eCallReasonHangup];
            return;
        }
    }
}

#pragma mark - public

- (void)jumpToChatList
{
    if ([self.navigationController.topViewController isKindOfClass:[ChatViewController class]]) {
        ChatViewController *chatController = (ChatViewController *)self.navigationController.topViewController;
        //        [chatController hideImagePicker];
    }
    else if([ChatListViewController chatlistViewController])
    {
    [self.navigationController popToViewController:self animated:NO];
       [Utils pushTabbarHidden:[ChatListViewController chatlistViewController] Selfvc:self];
    }
}

- (EMConversationType)conversationTypeFromMessageType:(EMMessageType)type
{
    EMConversationType conversatinType = eConversationTypeChat;
    switch (type) {
        case eMessageTypeChat:
            conversatinType = eConversationTypeChat;
            break;
        case eMessageTypeGroupChat:
            conversatinType = eConversationTypeGroupChat;
            break;
        case eMessageTypeChatRoom:
            conversatinType = eConversationTypeChatRoom;
            break;
        default:
            break;
    }
    return conversatinType;
}

- (void)didReceiveLocalNotification:(UILocalNotification *)notification
{
    NSDictionary *userInfo = notification.userInfo;
    if (userInfo)
    {
        if ([self.navigationController.topViewController isKindOfClass:[ChatViewController class]]) {
            ChatViewController *chatController = (ChatViewController *)self.navigationController.topViewController;
            //            [chatController hideImagePicker];
        }
        
        NSArray *viewControllers = self.navigationController.viewControllers;
        [viewControllers enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id obj, NSUInteger idx, BOOL *stop){
            if (obj != self)
            {
                if (![obj isKindOfClass:[ChatViewController class]])
                {
                    [self.navigationController popViewControllerAnimated:NO];
                }
                else
                {
                    NSString *conversationChatter = userInfo[kConversationChatter];
                    ChatViewController *chatViewController = (ChatViewController *)obj;
                    if (![chatViewController.conversation.chatter isEqualToString:conversationChatter])
                    {
                        [self.navigationController popViewControllerAnimated:NO];
                        EMMessageType messageType = [userInfo[kMessageType] intValue];
                        chatViewController = [[ChatViewController alloc] initWithConversationChatter:conversationChatter conversationType:[self conversationTypeFromMessageType:messageType]];
                        switch (messageType) {
                            case eMessageTypeGroupChat:
                            {
                                NSArray *groupArray = [[EaseMob sharedInstance].chatManager groupList];
                                for (EMGroup *group in groupArray) {
                                    if ([group.groupId isEqualToString:conversationChatter]) {
                                        chatViewController.title = group.groupSubject;
                                        break;
                                    }
                                }
                            }
                                break;
                            default:
                                chatViewController.title = conversationChatter;
                                break;
                        }
                        [self.navigationController pushViewController:chatViewController animated:NO];
                    }
                    *stop= YES;
                }
            }
            else
            {
                ChatViewController *chatViewController = (ChatViewController *)obj;
                NSString *conversationChatter = userInfo[kConversationChatter];
                EMMessageType messageType = [userInfo[kMessageType] intValue];
                chatViewController = [[ChatViewController alloc] initWithConversationChatter:conversationChatter conversationType:[self conversationTypeFromMessageType:messageType]];
                switch (messageType) {
                    case eMessageTypeGroupChat:
                    {
                        NSArray *groupArray = [[EaseMob sharedInstance].chatManager groupList];
                        for (EMGroup *group in groupArray) {
                            if ([group.groupId isEqualToString:conversationChatter]) {
                                chatViewController.title = group.groupSubject;
                                break;
                            }
                        }
                    }
                        break;
                    default:
                        chatViewController.title = conversationChatter;
                        break;
                }
                [self.navigationController pushViewController:chatViewController animated:NO];
            }
        }];
    }
    else if ([ChatListViewController chatlistViewController])
    {
        [self.navigationController popToViewController:self animated:NO];
        [Utils pushTabbarHidden:[ChatListViewController chatlistViewController] Selfvc:self];
    }
}

#pragma mark - IChatManagerDelegate 登录状态变化

- (void)didLoginFromOtherDevice
{
    [[EaseMob sharedInstance].chatManager asyncLogoffWithUnbindDeviceToken:NO completion:^(NSDictionary *info, EMError *error) {
        
        if(error){
            [HUD Prompt:@"网络错误"];
        }else{
            
            // [HUD Prompt:@"您的账号在别的地方登录"];
            [Utils alert:@"您的账号在别的地方登录"];
            //退出登录
            [Utils quitLogin];
            
            [self.navigationController popToRootViewControllerAnimated:NO];
            
            // 如果用户已填写了初始化信息
            UINavigationController *Login = [[UINavigationController alloc]initWithRootViewController:[[LoginViewController alloc]init]];
            Login.modalPresentationStyle = UIModalPresentationFormSheet;
            [self presentViewController:Login animated:NO completion:nil];
            
        }
    } onQueue:nil];
}



/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
